<template>
  <div style="padding: 0 5px">
    <a-spin :spinning="tableSpinning" size="large" :tip="$t('Loading-tip')">
    <NoAuthPage v-showNoAuth="'E10-1'" :imgBoxStyle="{height:'40vh',margin:'0 10px 10px'}"/>

    <div v-userAuth="'E10-1'">
      <div style="margin:10px 0 20px">
      <!--规则设置-->
      <a-button v-userAuth="'E10-2'" type="primary" @click="setRule_dialog = true">{{$t('Rule-setting')}}</a-button>
      <!--收集-->
      <a-button v-userAuth="'E10-3'" type="primary" style="margin:0 10px" 
                :disabled="selectedRowKeys.length==0 || isDisabledCollectBtn"
                @click="openCollectLog('multiple')">
        {{$t('Collected')}}
      </a-button>
      <!--手工清除-->
      <a-button v-userAuth="'E10-4'" type="primary" 
                :disabled="selectedRowKeys.length==0 || isDisabledClearBtn"
                @click="delSysLog('multiple')">
        {{$t('Manual-removal')}}
      </a-button>
      </div>
    
    <!--表格-->
    <a-table 
      :columns='columns' :rowSelection='{selectedRowKeys:selectedRowKeys,onChange:onSelectChange}' 
			:dataSource='tableData' :loading="tableLoading" size='small' bordered
			:pagination='pagination' :rowKey="(record) =>record.hostname+record.manage_ip" :locale="defaultSetting">
      <template slot="progress" slot-scope="text, record">
        <!--已完成-->
        <div v-if="record.state == 2">
          <span class="green-circle"></span><span>{{$t('Completed')}}</span>
        </div>
        <!--收集中-->
        <div v-else-if="record.state == 1">
          <span class="blue-circle"></span><span>{{$t('Collecting')}}</span>
        </div>
        <!--未收集-->
        <div v-else-if="record.state == 0">
          <span class="grey-circle"></span><span>{{$t('Not-collected')}}</span>
        </div>
      </template>
      <template slot="operation" slot-scope="text, record">
        <!-- :class="是否正在收集或者收集完成?'disabled-detail-text':'detail-text'" -->
        <!--收集-->
        <div class="img-box" v-userAuth="'E10-3'">
          <a-tooltip>
            <template slot="title">
              {{$t('Collected')}}
            </template>
            <!-- <i v-if="record.state != 1" class="icon icon-gather16f table-icon" @click="openCollectLog('single', record)"></i>
            <i v-else class="icon icon-gather16f img-cannot-click grey-icon"></i> -->
            <Iconfont v-if="record.state != 1" class="icon table-icon" type="icon-gather16f" @click="openCollectLog('single', record)"></Iconfont>
            <Iconfont v-else class="icon img-cannot-click grey-icon" type="icon-gather16f"></Iconfont>
          </a-tooltip>
        </div>
        <!--清除包-->
        <div class="img-box" v-userAuth="'E10-4'">
          <a-tooltip>
            <template slot="title">
              {{$t('Clear-package')}}
            </template>
            <!-- <i v-if="record.state == 2" class="icon icon-error64f table-icon" @click="delSysLog('single', record)"></i>
            <i v-else class="icon icon-error64f img-cannot-click grey-icon"></i> -->
            <Iconfont v-if="record.state == 2" class="icon table-icon" type="icon-error64f" @click="delSysLog('single', record)"></Iconfont>
            <Iconfont v-else class="icon img-cannot-click grey-icon" type="icon-error64f"></Iconfont>
          </a-tooltip>
        </div>
        <!--下载-->
        <div class="img-box" v-userAuth="'E10-5'">
          <a-tooltip>
            <template slot="title">
              {{$t('Download')}}
            </template>
            <!-- <i v-if="record.state == 2" class="icon icon-download16f table-icon" @click="downloadLog(record)"></i>
            <i v-else class="icon icon-download16f img-cannot-click grey-icon"></i> -->
            <a v-if="record.state == 2" :href='getDownloadHref(record)' download>
              <Iconfont class="icon table-icon" type="icon-download16f"></Iconfont>
              <!-- <Iconfont class="icon table-icon" type="icon-download16f" @click="downloadLog(record)"></Iconfont> -->
            </a>
            <Iconfont v-else class="icon img-cannot-click grey-icon" type="icon-download16f"></Iconfont>
          </a-tooltip>
        </div>
        <!--一键备份-->
        <div class="img-box" v-userAuth="'E10-6'">
          <a-tooltip>
            <template slot="title">
              {{$t('One-click-backup')}}
            </template>
            <!-- <i v-if="record.state == 2" class="icon icon-copy16f table-icon" @click="oneClickBackup(record)"></i>
            <i v-else class="icon icon-copy16f img-cannot-click grey-icon"></i> -->
            <Iconfont v-if="record.state == 2" class="icon table-icon" type="icon-copy16f" @click="oneClickBackup(record)"></Iconfont>
            <Iconfont v-else class="icon img-cannot-click grey-icon" type="icon-copy16f"></Iconfont>
          </a-tooltip>
        </div>
        <!-- <span class="detail-text" @click="openCollectLog('single', record)">{{$t('Collected')}}</span> -->
        <!-- <span class="disabled-detail-text">收集</span> -->
        <!-- <span class="detail-text" @click="delSysLog('single', record)">{{$t('Clear')}}</span> -->
        <!-- 是否收集完成?'detail-text':'disabled-detail-text' -->
        <!-- <span class="detail-text" @click="downloadLog(record)">{{$t('Download')}}</span> -->
        <!-- <span class="disabled-detail-tex">下载</span> -->
      </template>
    </a-table> 

    <!--系统日志收集记录-->
    <SystemLogRecord 
      @updateSystemLog="updateSystemLog"
      @changeSpinStatus="changeSpinStatus"
    />
    </div>

    <!--规则设置-->
    <SetRule 
      v-if="setRule_dialog"
      :visible="setRule_dialog" 
      @closeDialog="closeDialog"
      :defaultRules="defaultRules"
      @updateDefaultRule="updateDefaultRule"
    />

    <!--收集系统日志-->
    <CollectSystemLog 
      v-if="collectLog_dialog"
      :visible="collectLog_dialog"
      :targetRow="targetRow"
      @closeDialog="closeDialog"
      @updateTableData="updateTableData"
    />
    </a-spin>
  </div>
</template>

<script>
import EmptyData from '@/components/common/EmptyData'
import SetRule from '@/views/operation/log_manage/subpage/systemLogOper/SetRule'
import CollectSystemLog from '@/views/operation/log_manage/subpage/systemLogOper/CollectSystemLog'
import SystemLogRecord from '@/views/operation/log_manage/subpage/SystemLogRecord'
import NoAuthPage from '@/components/common/NoAuthPage'

import request from '@/request/request'

export default {
  name: "SystemLog",
  components: { SetRule, CollectSystemLog, SystemLogRecord, NoAuthPage },
  data() {
    return {
      selectedRowKeys: [],
      selectedRows: [],
      tableLoading: false,
      pagination:{
        defaultPageSize:5,
        showTotal: total => `${this.$t('A-total-of')} ${total} ${this.$t('Data')}`,
        showSizeChanger:true,
        pageSizeOptions:['5','10','15'],
        onShowSizeChange:(current,pageSize)=>this.pageSize = pageSize,
				buildOptionText: (props) => `${props.value} / ${this.$t('page')}`
      },
      defaultSetting: {emptyText:<EmptyData />},
      tableData: [],
      columns: [
        { title: this.$t('Manage-network'), dataIndex: 'manage_ip', key: 'manage_ip',ellipsis: true, },
        { title: this.$t('Node-name'), dataIndex: 'hostname', key: 'hostname',ellipsis: true, },
        { title: this.$t('Schedule'), dataIndex: 'progress', key: 'progress',scopedSlots:{customRender:'progress'}, },
        { title: this.$t('Log-size'), dataIndex: 'size', key: 'size',width:120,ellipsis: true, },
        { title: this.$t('Log-name'), dataIndex: 'name', key: 'name',ellipsis: true, },
        { title: this.$t('Operate'), dataIndex: 'oper', key: 'oper', scopedSlots:{customRender:'operation'},ellipsis: true, },
      ],
      isDisabledCollectBtn: false,
      isDisabledClearBtn: false,
      setRule_dialog: false,
      collectLog_dialog: false,
      targetRow: {},
      defaultRules: {},
      // userId: localStorage.getItem('user_id'),
      timer: null,
      tableSpinning: false,
    }
  },
  watch: {
    getlanguage() {
      this.columns = [
        { title: this.$t('Manage-network'), dataIndex: 'manage_ip', key: 'manage_ip',ellipsis: true, },
        { title: this.$t('Node-name'), dataIndex: 'hostname', key: 'hostname',ellipsis: true, },
        { title: this.$t('Schedule'), dataIndex: 'progress', key: 'progress',scopedSlots:{customRender:'progress'}, },
        { title: this.$t('Log-size'), dataIndex: 'size', key: 'size',width:120,ellipsis: true, },
        { title: this.$t('Log-name'), dataIndex: 'name', key: 'name',ellipsis: true, },
        { title: this.$t('Operate'), dataIndex: 'oper', key: 'oper', scopedSlots:{customRender:'operation'},ellipsis: true, },
      ];
    }
  },
  computed:{
		getlanguage(){
			return this.$store.state.language
		}
	},
  mounted() {
    this.getSystemTableData();
    this.getDefaultRule();
  },

  beforeDestroy() {
    clearTimeout(this.timer);
  },

  methods: {

    // 返回下载地址
    getDownloadHref(record) {
       return `${this.$protocolStr}${record.manage_ip}${this.$portStr}download/${record.name}`;
    },

    //获取系统日志上方表格信息
    getSystemTableData() {
      this.tableLoading = true;
      request('get', 'logmanage/syslog/nodes/',{
        // params: {
          // user_id: this.userId
        // }
      }).then(res => {
        // console.log('获取系统日志', res);
        if(res.data.flag == 1) {
          this.model(res.data.id) //返回模板
          this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
        }else {
          this.tableData = res.data;
        }
      }).catch(err => {
        console.log(err)
      }).finally(() => {
        this.tableLoading = false;
      })
    },

    //获取默认规则
    getDefaultRule() {
      request('get', 'logmanage/syslog/default/').then(res => {
        // console.log('获取默认规则', res)
        this.defaultRules = res.data;
      }).catch(err => {
        // console.log(err);
      })
    },

    onSelectChange(selectedRowKeys, selectedRows) {
      // selectedRows.forEach(item => {
      //   if(item.正在收集 || item.收集完成) {
      //     this.isDisabledCollectBtn = true;
      //   }
      //   if(item.未收集) {
      //     this.isDisabledClearBtn = true;
      //   }
      // })
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
    },

    //打开收集系统日志
    openCollectLog(type, record={}) {
      //多选情况
      if(type == 'multiple') {
        this.targetRow = this.selectedRows;
      }else if(type == 'single') {//单选
        this.targetRow = record;
      }
      this.collectLog_dialog = true;
    },

    //清除系统日志
    delSysLog(type, record={}) {
      let _this = this;
      let nodesStr = '';
      let flag = false;
      if(type == 'multiple') {
        this.selectedRows.some(item => {
          if(item.state !== 2) {
            flag = true;
            return true
          }
        })
        if(flag) {
          if(this.$store.state.language == 'zh') {
            this.$message.error('不能清除未收集包的节点');
          }else {
            this.$message.error('Cannot clear nodes that do not collect packages');
          }
          return
        }
        this.selectedRows.forEach((item,index) => {
          if(index == this.selectedRows.length -1) {
            nodesStr += `"${item.hostname}"`
          }else {
            nodesStr += `"${item.hostname}"、`
          }
        });
      }else if(type == 'single') {
        nodesStr = `"${record.hostname}"`;
      }
      this.$confirm({
        title: this.$t('Clear-system-log'),
        content: this.$store.state.language == 'zh'?
        `清除节点${nodesStr}已经收集的系统日志后，如需重新下载需要重新收集，该过程需要一定时间。您确定要清除吗？`
        :`After clearing the system logs that have been collected by node ${nodesStr}, if you need to download again, you need to collect again. This process takes some time. Are you sure you want to clear?`,
        cancelText:this.$t('Cancel'),
        okText:this.$t('Sure'),
        okType:'danger',
        async onOk(){
          _this.tableLoading = true;
          if(type == 'multiple') {
            _this.selectedRows.forEach(async (item,index) => {
              let params = {
                id: item.log_id, //日志主键
                name: item.name, //日志名称
                node: record.hostname,
                ipaddr: item.manage_ip
              }
              let res = await _this.clearLogRequest(item, params);
              if(res.data.flag != 0 || index == _this.selectedRows.length -1) {
                _this.updateDataAfterClear();
                _this.model(res.data.id) //返回模板
                _this.notice(res.data.id,res.data.params,res.data.flag) //通知列表显示
              }
            })
          }else {
            let res = await _this.clearLogRequest(record, {
              id: record.log_id, //日志主键
              name: record.name,  //日志名称
              node: record.hostname,
              ipaddr: record.manage_ip
            });
            _this.updateDataAfterClear();
            _this.model(res.data.id) //返回模板
            _this.notice(res.data.id,res.data.params,res.data.flag) //通知列表显示
          }
        },
        onCancel(){
          return;
        }
      })
    },

    //清除包后更新数据
    updateDataAfterClear() {
      this.$store.commit('updateCollectRecord', true);//更新日志记录表格数据
      this.tableLoading = false;
      this.selectedRowKeys = [];
    },

    //清除包请求方法
    clearLogRequest(record, params) {
      return new Promise((resolve, reject) => {
        request('DELETE', 'logmanage/syslog/',
        // {
        //   data: params
        // }
        params
        ).then(res => {
          // console.log('清除包',res)
          resolve(res);
          this.getSystemTableData();
        }).catch(err => {
          reject(err);
        })
      })
      
    },

    //下载系统日志
    downloadLog(record) {
      // this.tableLoading = true;
      this.tableSpinning = true;
      this.$message.success(this.$t('Downloading'));
      request('post','logmanage/syslog/download',{
        name: record.name
      },{
        responseType: 'blob'
      }).then(res => {
        // console.log('下载日志', res)
        if(res.status == 200) {
          this.downloadZip(res.data, record.name);
        }else {
          this.$message.error(this.$t('Download-fail'));
        }
      }).catch(err => {
        // console.log(err)
      }).finally(() => {
        // this.tableLoading = false;
        this.tableSpinning = false;
      })
    },
    //二进制流下载zip
    downloadZip(res,name) {
      let blob = new Blob([res], {type: `application/zip;`});
      // 获取heads中的filename文件名
      let downloadElement = document.createElement('a');
      // 创建下载的链接
      let href = window.URL.createObjectURL(blob);
      downloadElement.href = href;
      // 下载后文件名
      downloadElement.download = name;
      document.body.appendChild(downloadElement);
      // 点击下载
      downloadElement.click();
      // 下载完成移除元素
      document.body.removeChild(downloadElement);
      // 释放掉blob对象
      window.URL.revokeObjectURL(href);
      this.$message.success(this.$t('Download-success'));
    },

    //一键备份
    oneClickBackup(record) {
      this.tableLoading = true;
      request('post', 'logmanage/syslog/default/backup',{
        log_name: record.name, //日志名称
        log_id: record.log_id, //日志主键id,
        ipaddr: record.manage_ip
      }).then(res => {
        // console.log('一键备份', res)
        this.model(res.data.id) //返回模板
        this.notice(res.data.id,res.data.params,res.data.flag) //通知列表显示
      }).catch(err => {
        // console.log(err);
      }).finally(() => {
        this.tableLoading = false;
      })
    },

    closeDialog(type) {
      if(type == 'set_rule') {
        this.setRule_dialog = false;
      }else if(type == 'log') {
        this.collectLog_dialog = false;
      }
    },

    //收集日志后更新数据
    updateTableData() {
      this.selectedRowKeys = [];
      this.timer = setTimeout(() => {
        this.getSystemTableData();
      }, 1000)
    },

    //修改规则后，更新默认规则
    updateDefaultRule() {
      this.getDefaultRule();
    },

    //清除包后，更新上方表格
    updateSystemLog() {
      this.getSystemTableData();
    },

    //下载日志或下载完，加载状态的变化
    changeSpinStatus(value) {
      this.tableSpinning = value;
    }
  },
}
</script>
<style scoped>
  .detail-text {
    color: var(--themeColor);
    cursor: pointer;
    margin: 8px;
  }
  .disabled-detail-text {
    color: #999;
    cursor: not-allowed;
    margin: 8px;
  }
  .img-box {
    display: inline-block;
    margin: 0 8px;
  }
  .img-cannot-click {
    cursor: not-allowed;
  }
  .table-icon {
    cursor: pointer;
    color: var(--themeColor);
  }
  .grey-icon {
    color: #d6d6d6;
  }
</style>